package com.changgou.gateway.filter;

import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

/**
 * @ClassName AuthorizeFilter
 * @Description 过滤器
 * @Author 洛尘
 * @Date 17:28 2019/11/20
 * @Version 2.1
 **/
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization";
    private static final String LOGIN_URL = "http://localhost:9001/oauth/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();



      //1判断用户是否登录
        String url = request.getURI().getPath();
        if(URLFilter.hasAuthorize(url)){ //登录
            return chain.filter(exchange);
        }

        //2其他请求参数判断用户是否携带token
        String token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);
        //从请求头参数获取
        if (StringUtils.isEmpty(token)) {
            token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);
        }


        //3从cookie中获取cookie
        if (StringUtils.isEmpty(token)) {
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }


        //4 如果没有token不进行放行
        if (StringUtils.isEmpty(token)) {
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
            response.setStatusCode(HttpStatus.SEE_OTHER);   //303
            String path = LOGIN_URL+ "?from=" + request.getURI().toString(); //获取登录前的地址
            response.getHeaders().add("Location",path);     //设置到请求头中
            //发送请求
            return response.setComplete();
        }

        //解析token
        try {
            //Claims claims = JwtUtil.parseJWT(token);
            request.mutate().header(AUTHORIZE_TOKEN,"bearer "+ token);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }


}
